/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.gov.cemaden.pcd.file;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

/**
 *
 * @author alan
 */
public class CSVFileWriter {
    
    public void write(Path file, List<String[]> list, Character separator) {
                
        if(Files.notExists(file)){
            try{
                Files.createFile(file);
            }
            catch(IOException ex){
                System.err.printf("The attempt to create the file %s failed.%n%s", file.toAbsolutePath(), ex.getMessage());
            }
        }
        
        FileWriter writer = null;
        try {
            writer = new FileWriter(file.toFile());
        } catch (IOException ex) {
            System.err.printf("Error when trying to create FileWriter object.%n%s", ex.getMessage());
        }
        
        BufferedWriter buffer = new BufferedWriter(writer);						        
        for (String[] data : list) {
            String output = "";
            for (String string : data) {
                output = output.concat(String.format("%s%c", string, separator));                
            }
            try {
                buffer.write(String.format("%s%n", output));
            } catch (IOException ex) {
                System.err.printf("Error when trying to write the file.%n%s", ex.getMessage());
            }
        }
        try {
            buffer.close();
            System.out.printf("The file %s was created%n", file.toAbsolutePath());
        } catch (IOException ex) {
            System.err.printf("Error when trying to close the BufferedWriter object%n%s", ex.getMessage());
        }        
    }
    
}
